#!/usr/bin/env python
#!-*- coding:utf-8 -*-

from flask import render_template, Flask
import os
from geoconvTools import Geoconv
import webbrowser
import threading
import time
from vision_ruler.msg import points
import json
import rospy

camera_lat=None
camera_lon=None
target_lat=None
target_lon=None
browserOpened = False
geoconv = Geoconv()
lock=threading.Lock()
app = Flask(__name__, template_folder='../html', static_folder='../html/scripts')

@app.route("/")
def openMap():
    return render_template('map.html', jq_path='jquery.min.js')

@app.route("/getPoints")
def getPoints():
    global camera_lat, camera_lon, target_lat, target_lon
    lock.acquire()
    camera_lat_t=camera_lat
    camera_lon_t=camera_lon
    target_lat_t=target_lat
    target_lon_t=target_lon
    lock.release()
    if camera_lat is None:
        return json.dumps([])
    clon, clat = geoconv.wgs84tobd09(camera_lon_t, camera_lat_t)
    tlon, tlat = geoconv.wgs84tobd09(target_lon_t, target_lat_t)
    return json.dumps([clon,clat,tlon,tlat])

def spin():
    rospy.spin()

def gpsInfoCallback(data):
    global camera_lat, camera_lon, target_lat, target_lon, browserOpened
    lock.acquire()
    camera_lat=data.camera_lat
    camera_lon=data.camera_lon
    target_lat=data.target_lat
    target_lon=data.target_lon
    lock.release()
    if browserOpened == False:
        browserOpened = True
        webbrowser.open('http://localhost:5000', new=0)
    
if __name__ == '__main__':
    rospy.init_node("mapSever", anonymous=True)
    rospy.Subscriber("/gps_info", points, gpsInfoCallback)
    threading.Thread(target=spin, args=()).start()
    app.run()
